//
//  HomeVC.swift
//  NavPushAni
//
//  Created by 李煜 on 2022/8/18.
//

import UIKit

class HomeVC: UIViewController {
  var isPresented: Bool = false

  override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .white
    title = "home"
    setupNavBtn()
  }
  private func setupNavBtn() {
    let btn = UIButton()
    btn.setTitle("fold", for: .normal)
    btn.addTarget(self, action: #selector(clickNavBtn), for: .touchUpInside)
    btn.sizeToFit()
    btn.setTitleColor(.black, for: .normal)
    navigationItem.titleView = btn

  }
  @objc  func  clickNavBtn() {
    print("abc")
    isPresented.toggle()

    let popvc = PopVC()
    popvc.modalPresentationStyle = .custom
    popvc.transitioningDelegate = self
    present(popvc, animated: true)
  }


}

extension HomeVC : UIViewControllerTransitioningDelegate {
  func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
    return OMPresentationController(presentedViewController: presented, presenting: presenting)
  }
  func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
    isPresented = true
   return self
  }
  func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
    isPresented = false
    return self
  }
}

extension HomeVC: UIViewControllerAnimatedTransitioning {
  func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
    return 1
  }

  func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
    if isPresented {
      let presentedView = transitionContext.view(forKey: .to)
      presentedView!.transform =  CGAffineTransform(scaleX: 1, y: 0)
      presentedView?.layer.anchorPoint = .init(x: 0.5, y: 0)
//      添加
      transitionContext.containerView.addSubview(presentedView!)
      UIView.animate(withDuration: 1) {
        presentedView?.transform = .identity
      } completion: { isFinished in
        if isFinished {
          transitionContext.completeTransition(isFinished)
        }
      }

    }else{
      let fromView = transitionContext.view(forKey: .from)

      fromView?.layer.anchorPoint = .init(x: 0.5, y: 0)
      //      添加
      transitionContext.containerView.addSubview(fromView!)
      UIView.animate(withDuration: 1) {
        fromView!.transform =  CGAffineTransform(scaleX: 1, y: 0.001)

      } completion: { isFinished in
        if isFinished {
          fromView?.removeFromSuperview()
          transitionContext.completeTransition(isFinished)
        }
      }
    }
  }

  
}
